package com.yeren.file;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 *在指定路径按照指定的文件格式和写入内容，写入TXT文件中，并且读出来打印
 * @author liubiao
 */
public class writeFileAndReadFileByContentAndEncodingToPath {
		//按指定编码写
		public static void write(String path, String content, String encoding)throws IOException {
			//在指定路径新建一个文件，如果该文件存在删除了，重新建一个文件
			File file = new File(path);
			file.delete();
			file.createNewFile();
			//文件输出流
			FileOutputStream fos=new FileOutputStream(file);
			//
			OutputStreamWriter osw=new OutputStreamWriter(fos,encoding);
			BufferedWriter bw=new BufferedWriter(osw);
			bw.write(content);
			bw.close();
		}

		//按指定编码读
		public static String read(String path, String encoding) throws IOException {
			String content = "";
			File file = new File(path);
			//
			FileInputStream fis=new FileInputStream(file);
			InputStreamReader isr=new InputStreamReader(fis,encoding);
			BufferedReader br=new BufferedReader(isr);
			String temp = null;
			while ((temp = br.readLine()) != null) {
				content += temp + "\n";
			}
			br.close();
			return content;
		}

		public static void main(String[] args) throws IOException {
			//内容
			String content = "Hello,刘彪!";
			//读写的路径
			String path = "d:/123.txt";
			//编码集
			String encoding = "utf-8";
			write(path, content, encoding);
			System.out.println(read(path, encoding));
		}
	}